package com.house365.core.view.pinned;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import android.content.Context;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.SectionIndexer;

import com.house365.core.adapter.BaseListAdapter;
import com.house365.core.constant.CorePreferences;
import com.house365.core.view.pinned.MySectionIndexer.IndexerRanger;
import com.house365.core.view.pinned.PinnedHeaderListView.PinnedHeaderAdapter;

/**
 * Adapter for sections.
 * @Midifier Rick Ping
 */
public abstract class BaseSectionListAdapter extends BaseListAdapter<SectionListItem>
		implements OnItemClickListener, PinnedHeaderAdapter, SectionIndexer,
		OnScrollListener {
	private MySectionIndexer mIndexer;
	private String[] mSections;// 所有分组的名字
	private int[] mCounts;// 所有分组的个数
	private int mSectionCounts = 0;

	private final Map<String, View> currentViewSections = new HashMap<String, View>();
	protected final LayoutInflater inflater;

	private View transparentSectionView;

	private SectionListItemClickListener linkedListener;

	public BaseSectionListAdapter(Context context) {
		super(context);
		this.inflater = LayoutInflater.from(context);
	}
	@Override
	public boolean addAll(List<? extends SectionListItem> list) {
		super.addAll(list);
		mSectionCounts =0;
		updateTotalCount();
		mIndexer = new MySectionIndexer(mSections, mCounts);
		return true;
	}
	private boolean isTheSame(final String previousSection,
			final String newSection) {
		if (previousSection == null) {
			return newSection == null;
		} else {
			return previousSection.equals(newSection);
		}
	}

	// add by lcq:2011-12-17 模拟得到indexer的数据
	private void fillSections() {
		mSections = new String[mSectionCounts];
		mCounts = new int[mSectionCounts];
		final int count = getCount();
		String currentSection = null;
//		int newSectionIndex = 0;
//		int newSectionCounts = 0;
		int newSectionIndex = -1;
		int newSectionCounts = 1;
		String previousSection = null;
		for (int i = 0; i < count; i++) {
			newSectionCounts++;
			currentSection = getItem(i).section;
//			if (!isTheSame(previousSection, currentSection)) {
//				mSections[newSectionIndex] = currentSection;
//				previousSection = currentSection;
//				if (newSectionIndex == 1) {// 如果是首次开始，则减1(因为第一次进入循环时，前一个为空，相当于indexCount多加了一次)
//					mCounts[0] = newSectionCounts - 1;
//				} else if (newSectionIndex != 0) {
//					mCounts[newSectionIndex - 1] = newSectionCounts;
//				}
//				if (i != 0) {// 首次进入，计数不置0，其他情况，重新计数
//					newSectionCounts = 0;
//				}
//				newSectionIndex++;
//			} else if (i == count - 1) {// 如果是最后一个,因为进入的时候把newSectionCounts置为0，下次不会计数，少加了一次
//				mCounts[newSectionIndex - 1] = newSectionCounts + 1;
//			}
			if (!isTheSame(previousSection, currentSection)) {
				newSectionIndex++;
				newSectionCounts=1;
				mSections[newSectionIndex] = currentSection;
				previousSection = currentSection;
				mCounts[newSectionIndex] = newSectionCounts;
				
			}else{
					mCounts[newSectionIndex] = newSectionCounts;
			}
		}
		/*
		for(String a : mSections) {
			System.out.println(a);
		}
		*/
		// for(int a : mCounts)
		// System.out.println(a);
	}

	private synchronized void updateTotalCount() {
		String currentSection = null;
		final int count = getCount();
		for (int i = 0; i < count; i++) {
			final SectionListItem item = 
					getItem(i);
			if (!isTheSame(currentSection, item.section)) {
				mSectionCounts++;
				currentSection = item.section;
			}
		}
		fillSections();
	}


	public synchronized String getSectionName(final int position) {
		return null;
	}

	protected Integer getLinkedPosition(final int position) {
		return position;
	}


	// private View getSectionView(final View convertView, final String section)
	// {
	// View theView = convertView;
	// if (theView == null) {
	// // theView = createNewSectionView();
	// }
	// setSectionText(section, theView);
	// replaceSectionViewsInMaps(section, theView);
	// return theView;
	// }


	protected synchronized void replaceSectionViewsInMaps(final String section,
			final View theView) {
		if (currentViewSections.containsKey(theView)) {
			currentViewSections.remove(theView);
		}
		currentViewSections.put(section, theView);
	}

	// protected View createNewSectionView() {
	// return inflater.inflate(R.layout.section_view, null);
	// }

	@Override
	public View getView(final int position, final View convertView,
			final ViewGroup parent) {
		 
		int section = getSectionForPosition(position);
		boolean showHeader = false;
		if(getCount()==1){
			showHeader = true;
		}else{
			showHeader = getPositionForSection(section) == position;
		}
		//CorePreferences.DEBUG("position:"+position+",showHeader:"+showHeader);
//		
//		if(isHeader){
//			int nextSectionPosition = getPositionForSection(section + 1);
//			linkedListener.onHeaderItemClick(parent, view, position, nextSectionPosition-1);
		
		
		SectionView sectionView = initView(position, convertView, parent, showHeader);
		if(showHeader){
//			int nextSectionPosition = getPositionForSection(section + 1);
//			final int endPosition = nextSectionPosition-1;
			final IndexerRanger indexerRanger = mIndexer.getIndexerRanger(section);
			sectionView.header.setOnClickListener(new View.OnClickListener() {
				
				@Override
				public void onClick(View v) {
					if(indexerRanger!= null){
						linkedListener.onHeaderItemClick( convertView, indexerRanger.start, indexerRanger.end);
					}else{
						linkedListener.onHeaderItemClick( convertView, position, -1);
					}
				}
			});
		}
		return sectionView.view;
	}
	public class SectionView{
		public View view,header;
	}
	public abstract SectionView initView(final int position, final View convertView,
			final ViewGroup parent,boolean showHeader);



	public int getRealPosition(int pos) {
		return pos - 1;
	}

	public synchronized View getTransparentSectionView() {
		if (transparentSectionView == null) {
			// transparentSectionView = createNewSectionView();
		}
		return transparentSectionView;
	}

	protected void sectionClicked(final String section) {
		// do nothing
	}

	@Override
	public void onItemClick(final AdapterView<?> parent, final View view,
			final int position, final long id) {
		//CorePreferences.DEBUG("onItemClick:"+getPinnedHeaderState(position));
		if (linkedListener != null) {
//			int section = getSectionForPosition(position);
//			boolean isHeader = getPositionForSection(section) == position;
//			
//			if(isHeader){
//				int nextSectionPosition = getPositionForSection(section + 1);
//				linkedListener.onHeaderItemClick(parent, view, position, nextSectionPosition-1);
//			}else{
				linkedListener.onSubItemClick(parent, view, getLinkedPosition(position), id);
//			}
			
		}

	}
	/**
	 * 点击事件
	 * @author py
	 *
	 */
	public interface SectionListItemClickListener{
		public void onSubItemClick(final AdapterView<?> parent, final View view,
				final int position, final long id);
		public void onHeaderItemClick(final View view,
				final int startposition, final int endposition);
	}
	public void setOnItemClickListener(final SectionListItemClickListener linkedListener) {
		this.linkedListener = linkedListener;
	}

	@Override
	public int getPinnedHeaderState(int position) {
		int realPosition = position;// 这里没什么别的意思，主要是通讯录中，listview中第一个显示的是所有的联系人，
									// 不是真实的数据，所以会-1,这里偷懒，直接把后面的去掉，还有其他有类似的地方，原因一样
		if (mIndexer == null) {
			return PINNED_HEADER_GONE;
		}
		if (realPosition < 0) {
			return PINNED_HEADER_GONE;
		}
		int section = getSectionForPosition(realPosition);// 得到此item所在的分组位置
		int nextSectionPosition = getPositionForSection(section + 1);// 得到下一个分组的位置
		if (nextSectionPosition != -1
				&& realPosition == nextSectionPosition - 1) {
			return PINNED_HEADER_PUSHED_UP;
		}
		return PINNED_HEADER_VISIBLE;
	}

	@Override
	public void configurePinnedHeader(View header, int position, int alpha) {

		int realPosition = position;
		int section = getSectionForPosition(realPosition);

		String title;
		try {
			title = (String) mIndexer.getSections()[section];
//			CorePreferences.DEBUG("section r:"+section+",title:"+title);
			setHeaderViewText(header,title);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			title = (String) mIndexer.getSections()[0];
			CorePreferences.ERROR("section e:"+section+",title:"+title);
			setHeaderViewText(header,title);
			e.printStackTrace();
		}
		//((TextView) header.findViewById(R.id.header_text)).setText(title);
		
	}
	public abstract void setHeaderViewText(View header,String title);
	@Override
	public Object[] getSections() {
		if (mIndexer == null) {
			return new String[] { "" };
		} else {
			return mIndexer.getSections();
		}
	}

	@Override
	public int getPositionForSection(int section) {
		if (mIndexer == null) {
			return -1;
		}
		return mIndexer.getPositionForSection(section);
	}

	@Override
	public int getSectionForPosition(int position) {
		if (mIndexer == null) {
			CorePreferences.ERROR("mIndexer is null");
			return -1;
		}
		return mIndexer.getSectionForPosition(position);
	}

	@Override
	public void onScrollStateChanged(AbsListView view, int scrollState) {

	}

	@Override
	public void onScroll(AbsListView view, int firstVisibleItem,
			int visibleItemCount, int totalItemCount) {
		if (view instanceof PinnedHeaderListView) {
			((PinnedHeaderListView) view).configureHeaderView(firstVisibleItem);
		}

	}

}
